<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    protected $table = 'category';

    public $timestamps = false;

    protected $guarded = [''];

    /**
     *自连接 获取父分类
     */
    public function pCategory()
    {
        return $this->belongsTo('App\Models\category', 'upid', 'id');
    }

    /**
     * 返回缓存或者更新缓存
     *
     * @return array
     */
    static function cache($cache = 0)
    {

        $data = \Cache::has('category') ? \Cache::get('category') : false;
        if ($data === false || $cache) {
            $data = array();
            $categories = self::whereRaw('status = 1')->orderBy('sort')->get();
            foreach ($categories as $category) {
                $data[$category->id] = $category->toArray();
            }
            \Cache::add('category', $data, 86400);
        }

        return $data;
    }
}
